﻿using MQTTnet;
using MQTTnet.Client;
using System.Text;

namespace Manager.Service
{
    public class MqttService
    {
        private readonly IMqttClient _client;

        public MqttService(IMqttClient client)
        {
            _client = client;
        }

        public async Task PublishLargeMessageAsync(string topic, string message)
        {
            var mqttMessage = new MqttApplicationMessageBuilder()
                .WithTopic(topic)
                .WithPayload(Encoding.UTF8.GetBytes(message))
                .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
                .WithRetainFlag()
                .Build();
            try
            {
                await _client.PublishAsync(mqttMessage);
                Console.WriteLine("消息发送成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
